//
//  DeviceSelectedListViewController.swift
//  TJJPT
//
//  Created by FENGYL on 2017/5/31.
//  Copyright © 2017年 FENGYL. All rights reserved.
//

import UIKit
import MJRefresh

class DeviceSelectedListViewController: UIViewController,UISearchControllerDelegate,UITableViewDelegate,UITableViewDataSource {

    let searchResult = SearchResult()
    var searchResultViewController = UIViewController.init()
    var searchResultTableView = UITableView.init()
    var searchController:UISearchController?
    
    @IBOutlet weak var searchBarView: UIView!
    @IBOutlet weak var deviceTableView: UITableView!
    
    var rightBarButtonItem:UIBarButtonItem?
    var userName:String?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.setUpView()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewDidAppear(_ animated: Bool) {
        
        if userName != UserModel.userModel.userName {
            
            self.deviceTableView.mj_header.beginRefreshing()
            
        }
        
        self.deviceTableView.reloadData()
        
    }
    
    // MARK: - 初始化
    func setUpView() {
        
        searchResult.deviceSelectedListViewController = self
        searchResult.searchTableView = searchResultTableView
        
        // MARK: 初始化searchBAR
        self.setUpSearchBar()
        
        // MARK: 用于判断是否注销登录过第二个账号
        self.userName = UserModel.userModel.userName
        
        // MARK: 设置nav标题
        self.title = NSLocalizedString(LOCALIZABLE_STRING_DEVICE_SELECTION, comment: "")
        
        // MARK: 设置nav右item
        self.rightBarButtonItem = UIBarButtonItem.init(title: NSLocalizedString(LOCALIZABLE_STRING_REFRESH, comment: ""), style: .done, target: self, action: #selector(rightItemAction))
        self.navigationItem.rightBarButtonItem = self.rightBarButtonItem
        
        
        
        
        // MARK: 设置tableview
        self.deviceTableView.delegate = self
        self.deviceTableView.dataSource = self
        self.deviceTableView.tableFooterView = UIView.init()
        self.deviceTableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            
            print("hhh")
            
            NetworkCommand.GetDevicesByAccount(id: nil, clientType: nil, tokenPass: nil, success: { (response) in
                
                NetworkCommand.getLastStatusData(listSerialNumber: nil, id: nil, clientType: nil, tokenPass: nil, success: { (response1) in
                    
                    NetworkCommand.autoChangeSelectedSerialNumber()
                    
                    self.deviceTableView.reloadData()
                    
                    self.deviceTableView.mj_header.endRefreshing()
                    
                }, failure: { (Error) in
                    
                    self.deviceTableView.mj_header.endRefreshing()
                    
                })
                
                
                
            }, failure: { (Error) in
                
                self.deviceTableView.mj_header.endRefreshing()
                
            })
            
            
            
            
            
        })
        
        self.deviceTableView.mj_header.beginRefreshing()
        
    }
    
    
    // MARK: - 初始化searchbar
    func setUpSearchBar() {
        
        searchController = UISearchController.init(searchResultsController: searchResultViewController)
        
        
        
        searchController?.delegate = searchResult
        
        searchController?.searchBar.delegate = searchResult
        
        searchController?.searchBar.frame = searchBarView.bounds
        
        searchBarView.addSubview((searchController?.searchBar)!)
        
        // MARK: 添加tableview
        searchResultViewController.automaticallyAdjustsScrollViewInsets = false
        
        let navHeight = (self.navigationController?.navigationBar.height)! + 20
        
        let tabHeight = self.navigationController?.tabBarController?.tabBar.height
        
        searchResultTableView.frame = CGRect.init(x: 0, y: navHeight, width: STATIC_VALUE_SCREEN_WIDTH, height: STATIC_VALUE_SCREEN_HEIGHT - navHeight - tabHeight!)
        
        searchResultTableView.tableFooterView = UIView.init()
        
        searchResultTableView.delegate = searchResult
        
        searchResultTableView.dataSource = searchResult
        
        searchResultViewController.view.addSubview(searchResultTableView)
        
        
        
        
    }
    
    // MARK: - 刷新
    func rightItemAction() {
        
        self.deviceTableView.mj_header.beginRefreshing()
        
    }
    
    
    // MARK: - tableView相关
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if UserModel.userModel.lastStatusDataArray != nil {
            
            return (UserModel.userModel.lastStatusDataArray?.count)!
            
        }
        
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell:DeviceSelectedListTableViewCell
        
        if (tableView.dequeueReusableCell(withIdentifier: "DeviceSelectedListTableViewCell") != nil) {
            
            cell = tableView.dequeueReusableCell(withIdentifier: "DeviceSelectedListTableViewCell") as! DeviceSelectedListTableViewCell
            
        }else{
            
            cell = DeviceSelectedListTableViewCell.init(style: .default, reuseIdentifier: "DeviceSelectedListTableViewCell")
            
        }
        
        let dict = UserModel.userModel.lastStatusDataArray?[indexPath.row]
        
        let lastStatusData:LastStatusData = LastStatusData.mj_object(withKeyValues: dict)
        
        
        // MARK: 是否在线
        var online = false
        
//        if (lastStatusData.ConnStatus != nil) {
//            
//            let status:NSNumber = dict.value(forKey: NETWORK_COMMAND_KEY_CONN_STATUS) as! NSNumber
        
            if lastStatusData.ConnStatus == 1 {
                
                online = true
                
            }
            
//        }
        
        
        // MARK: 是否选中
        var selected = false
        
        let serialNumber:String = lastStatusData.SerialNumber!
        
        if (UserModel.userModel.selectedDeviceSerialNumber.isEmpty) {
            
            NetworkCommand.autoChangeSelectedSerialNumber()
            
        }else{
            
            if UserModel.userModel.selectedDeviceSerialNumber == serialNumber {
                
                selected = true
                
            }
            
        }
        
        
        
        
        // MARK: 设备名
        var deviceName:String = serialNumber
        
        for accountDict in UserModel.userModel.devicesByAccountArray! {
            
            let deviceByAccount = DevicesByAccount.mj_object(withKeyValues: accountDict)
            
            let serialNum:String = (deviceByAccount?.SerialNumber)!
            
            if serialNum == serialNumber {
                
                deviceName = deviceByAccount?.DisplayName ?? serialNumber
                
            }
            
        }
        
        
        // MARK: 最后连接时间
        var lastConnectedString = NSLocalizedString(LOCALIZABLE_STRING_LAST_CONNECTED, comment: "")  + ":\n"
        
        let timeStamp:NSNumber = lastStatusData.ConnTime!
        
        let timeString = NetworkCommand.timestampToString(timestamp: timeStamp)
        
        lastConnectedString = lastConnectedString + timeString
        
        
        
        cell.setUpCell(online: online, selected: selected, deviceName: deviceName, lastConnected: lastConnectedString, serialNumber: serialNumber)
        
        cell.selectionStyle = .none
        
        return cell
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
//        tableView.deselectRow(at: indexPath, animated: true)
        
        let cell:DeviceSelectedListTableViewCell = tableView.cellForRow(at: indexPath) as! DeviceSelectedListTableViewCell
        
        let serialNumber = cell.deviceSerialNumber.text
        
        UserModel.userModel.selectedDeviceSerialNumber = serialNumber ?? ""
        
        tableView.reloadData()
        
    }
    
    
    // MARK: - searchbar delegate
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        
        
        
    }
    
    func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
        
        
        
        return true
        
    }

    /*
     
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

class SearchResult: NSObject,UISearchControllerDelegate,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate {
    
    let identifier = "SearchResult"
    var searchArray = [DevicesByAccount]()
    
    var deviceSelectedListViewController:DeviceSelectedListViewController?
    var searchTableView:UITableView?
    
    // MARK: - tableView相关
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return searchArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell:DeviceSelectedListTableViewCell
        
        if (tableView.dequeueReusableCell(withIdentifier: identifier) != nil) {
            
            
            
            cell = tableView.dequeueReusableCell(withIdentifier: identifier) as! DeviceSelectedListTableViewCell
            
            
            
        }else{
            
            cell = Bundle.main.loadNibNamed("SearchBarCellView", owner: self, options: nil)!.last as! DeviceSelectedListTableViewCell
            
//            cell = DeviceSelectedListTableViewCell.init(style: .default, reuseIdentifier: identifier)
            
        }
        
//        let dict = UserModel.userModel.lastStatusDataArray?[indexPath.row]
        
        var lastStatusData:LastStatusData?
        
        let devicesByAccount = searchArray[indexPath.row]
        
        if UserModel.userModel.lastStatusDataArray != nil {
            
            if (UserModel.userModel.lastStatusDataArray?.count)! > 0 {
                
                
                for dict in UserModel.userModel.lastStatusDataArray! {
                    
                    let last = LastStatusData.mj_object(withKeyValues: dict)
                    
                    if last?.SerialNumber == devicesByAccount.SerialNumber {
                        
                        lastStatusData = last
                        
                    }
                    
                }
                
                
            }
            
        }
        
        
        // MARK: 是否在线
        var online = false
        
        //        if (lastStatusData.ConnStatus != nil) {
        //
        //            let status:NSNumber = dict.value(forKey: NETWORK_COMMAND_KEY_CONN_STATUS) as! NSNumber
        
        if lastStatusData?.ConnStatus == 1 {
            
            online = true
            
        }
        
        //        }
        
        
        // MARK: 是否选中
        var selected = false
        
        let serialNumber:String = lastStatusData!.SerialNumber!
        
        if (UserModel.userModel.selectedDeviceSerialNumber.isEmpty) {
            
            NetworkCommand.autoChangeSelectedSerialNumber()
            
        }else{
            
            if UserModel.userModel.selectedDeviceSerialNumber == serialNumber {
                
                selected = true
                
            }
            
        }
        
        
        // MARK: 设备名
        var deviceName:String = serialNumber
        
        for accountDict in UserModel.userModel.devicesByAccountArray! {
            
            let devicesByAccount = DevicesByAccount.mj_object(withKeyValues: accountDict)
            
            let serialNum:String = devicesByAccount?.SerialNumber ?? ""
            
            if serialNum == serialNumber {
                
                deviceName = devicesByAccount?.DisplayName ?? serialNumber
                
            }
            
        }
        
        
        // MARK: 最后连接时间
        var lastConnectedString = NSLocalizedString(LOCALIZABLE_STRING_LAST_CONNECTED, comment: "")  + ":\n"
        
        let timeStamp:NSNumber = lastStatusData!.ConnTime!
        
        let timeString = NetworkCommand.timestampToString(timestamp: timeStamp)
        
        lastConnectedString = lastConnectedString + timeString
        
        
        
        cell.setUpCell(online: online, selected: selected, deviceName: deviceName, lastConnected: lastConnectedString, serialNumber: serialNumber)
        
        cell.selectionStyle = .none
        
        return cell
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        //        tableView.deselectRow(at: indexPath, animated: true)
        
        let cell:DeviceSelectedListTableViewCell = tableView.cellForRow(at: indexPath) as! DeviceSelectedListTableViewCell
        
        let serialNumber = cell.deviceSerialNumber.text
        
        UserModel.userModel.selectedDeviceSerialNumber = serialNumber ?? ""
        
        tableView.reloadData()
        
    }
    
    
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        
        
        if UserModel.userModel.devicesByAccountArray != nil {
            
            if (UserModel.userModel.devicesByAccountArray?.count)! > 0 {
                
                searchArray.removeAll()
                
                for dict in UserModel.userModel.devicesByAccountArray! {
                    
                    let devicesByAccount = DevicesByAccount.mj_object(withKeyValues: dict)
                    
                    var displayName = devicesByAccount?.SerialNumber
                    
                    if devicesByAccount?.DisplayName != nil {
                        
                        displayName = devicesByAccount?.DisplayName
                        
                    }
                    
                    if (displayName?.contains(searchBar.text!))! {
                        
                        searchArray.append(devicesByAccount!)
                        
                    }
                    
                    
                }
                
                searchTableView?.reloadData()
                
            }
            
        }
        
    }
    
    func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
        
        deviceSelectedListViewController?.deviceTableView.reloadData()
        
        return true
        
    }
    
}
